package com.example.yunbiji0314.service.iml;

import com.example.yunbiji0314.dao.GoodDao;
import com.example.yunbiji0314.dao.OrderDao;
import com.example.yunbiji0314.dao.OrderGoodDao;
import com.example.yunbiji0314.pojo.Good;
import com.example.yunbiji0314.pojo.Order;
import com.example.yunbiji0314.pojo.OrderGood;
import com.example.yunbiji0314.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional(rollbackFor = Exception.class)
@Service
public class OrderServiceImpl implements OrderService {

    //订单表接口
    @Autowired
    private OrderDao orderDao;

    //订单商品表接口
    @Autowired
    private OrderGoodDao orderGoodDao;

    @Autowired
    private GoodDao goodDao;

    @Override
    public void addOrder(Map map) {
        //从map中获取数据
        Integer uid = 0;
        //判断用户编号是否为空
        Object uid1 = map.get("uid");
        if (uid1!=null){
            uid =(Integer) uid1;
        }
        //获取订单总金额
        Object sum1 = map.get("sum");
        //创建订单对象
        Order order = new Order();
        order.setUid(uid);
        order.setMoney(Double.parseDouble(sum1.toString()));
        //插入订单表
        orderDao.addOrder(order);

        //创建订单商品集合
        List<OrderGood> orderGoodList = new ArrayList<>();

        //从map中获取订单商品信息（集合）
        List<Map> list = (List<Map>) map.get("goods");
        //创建订单商品对象
        OrderGood orderGood = new OrderGood();
        //遍历集合
        for (Map item : list) {
            Object oid = item.get("shangid");
            Object count = item.get("shangcount");
            Object jiaqian = item.get("sum");


            orderGood.setOid(order.getId());
            orderGood.setAid((Integer) oid);
            orderGood.setCount((Integer) count);
            orderGood.setMoney(Double.parseDouble(jiaqian.toString()));

            System.out.println(orderGood.getAid());
            //根据商品id查询商品信息
            goodDao.gengxin(orderGood.getAid());

            //添加订单商品
            orderGoodList.add(orderGood);
        }

        //添加订单商品
        orderGoodDao.addOrderGood(orderGoodList);


    }
}
